package io.afu.baseframework.annotations.impls;

import io.afu.baseframework.annotations.Permission;
import io.afu.baseframework.annotations.UAHas;
import io.afu.baseframework.utils.CommonUtils;
import io.afu.common.constant.ConstantEnum;
import io.afu.common.exception.BaseException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Aspect
@Component
public class UAHasImpl {

    private final Logger logger = LoggerFactory.getLogger(getClass());


    @Pointcut(value = "@annotation(io.afu.baseframework.annotations.UAHas)")
    public void cutCheckUserAgent(){

    }


    @Around("cutCheckUserAgent()")
    public Object checkUserAgent(ProceedingJoinPoint point) throws Throwable {
        //先执行业务
        BaseException baseException = null;
        logger.info("检查UserAgent");
        MethodSignature ms = (MethodSignature) point.getSignature();
        Method method = ms.getMethod();
        UAHas uaHas = method.getAnnotation(UAHas.class);
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null){
            throw new BaseException(ConstantEnum.API_HAS_NO_PERMISSION);
        }
        HttpServletRequest request = requestAttributes.getRequest();
        HttpServletResponse response = requestAttributes.getResponse();
        String[] useragents = uaHas.prefixes();
        if (useragents.length >0){
            String requestUserAgent = request.getHeader("User-Agent");
            // 在获取到的UserAgent中查找是否包含指定的前缀
            for (String useragent : useragents) {
                if (requestUserAgent.contains(useragent)){
                    return point.proceed();
                }
            }
            // 检查结束不包含指定的UserAgent 前缀，因此返回错误
            baseException = new BaseException(ConstantEnum.API_HAS_NO_PERMISSION);
        }
        if (baseException != null){
            CommonUtils.flushOut(response,baseException);
            return null;
        }
        return point.proceed();
    }




}
